﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TalentDesk.Mvc.Models;
using TalentDesk.Contracts.Ef;
using TalentDesk.Mvc.HelperClasses;
using TalentDesk.Contracts.ServiceContracts;
using SharedContracts.Types;

namespace TalentDesk.Mvc.Controllers
{
    public class AccountController : BaseController
    {

        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "SHA1")))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);


                    User result = null;
                    new ProxyHelper<IAuthenticationService>().Use(serviceProxy =>
                    {
                        result = serviceProxy.AuthenticateUser(model.UserName, FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "SHA1"));
                        Session.Add("User", result);

                    },
                       EndpointConstants.BasicHttpBinding_IAuthenticationService);
                    MessageBox("", EnumMessageType.Bos);

                    if (result != null)
                    {



                        Session["Menu"] = AuthenticationProxy.GetMenus().Where(p=>p.ParentMenuId==null).ToList();
                      
                      
                        if (returnUrl == "" || returnUrl == null)
                            return RedirectToAction("Index", "Home");
                        else
                            return Redirect(returnUrl);

                    }


                    return RedirectToAction("Login", "Account");
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }


            }

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();


            return RedirectToAction("Login", "Account");
        }

        [HttpGet]
        public ActionResult SessionExpired()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SessionExpiredPost()
        {
            return RedirectToAction("Login", "Account");
        }
    }
}
